package t20240902_udf;

import com.fasterxml.jackson.databind.JsonNode;
import com.maxmind.db.Reader;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.net.InetAddress;

public class IpHelper {

	public @interface IpJsonKeys {
		String IP_COUNTRY = "country";
		String IP_PROV = "prov";
		String IP_ISP = "isp";
		String IP_CITY = "city";
	}

	public static final String DEFAULT_CODE = "0";

	protected static final String SECRET_KEY_FILE = "D:\\code\\flink-all\\flink_demo\\secret.key";
	public static final String OUTPUT_DEL = ",";

	public static final String NULL_IP_CODE = "0,0,0,0";

	/**
	 * 封装IP解析的结果
	 * @param address
	 * @param readerV6
	 * @return String
	 */
	public static String generateIpInfo(InetAddress address, Reader readerV6) {
		try {
			JsonNode response = readerV6.get(address);
			if(response != null){
				// Parsing
				String country = response.get(IpJsonKeys.IP_COUNTRY).toString();
				String province = response.get(IpJsonKeys.IP_PROV).toString();
				String isp = response.get(IpJsonKeys.IP_ISP).toString();
				String city= response.get(IpJsonKeys.IP_CITY).toString();

				// Checking parsed value
				if (country.equals(null)){
					country = IpHelper.DEFAULT_CODE;
				}
				if (province.equals(null)){
					province = IpHelper.DEFAULT_CODE;
				}
				if (isp.equals(null)){
					isp = IpHelper.DEFAULT_CODE;
				}
				if (city.equals(null)){
					city= IpHelper.DEFAULT_CODE;
				}

				// Output format is: country province city isp
				return new StringBuffer().append(country).append(IpHelper.OUTPUT_DEL)
						.append(province).append(IpHelper.OUTPUT_DEL)
						.append(city).append(IpHelper.OUTPUT_DEL).append(isp)
						.toString();
			}
		} catch (Exception e){
			// do nothing here
		}
		return NULL_IP_CODE;
	}

	/**
	 * 解析出key与iv
	 * @param fs
	 * @return String[0] key
	 * 			String[1] iv
	 */
	public static String[] parseSecretKey(FileSystem fs){
		ByteArrayOutputStream outSteam = null;
		String [] tempStr = null;
		InputStream is = null;
		try{
			is = fs.open(new Path(IpHelper.SECRET_KEY_FILE));
			outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = is.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			tempStr = outSteam.toString().split("@");
		}catch (Exception ex){

		}finally {
			closeStream(outSteam);
			closeStream(is);
		}
		return tempStr;
	}

	/**
	 * 对实现Closeable的对象执行close操作
	 * @param obj
	 */
	public static void closeStream(Closeable obj){
		if(obj == null) return;
		try{
			obj.close();
		}catch (Exception ex){}
	}

}
